package com.huiyuanai.controller;

import com.huiyuanai.pojo.Department;
import com.huiyuanai.pojo.Employee;
import com.huiyuanai.service.DepartmentService;
import com.huiyuanai.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

/**
 * @Author: liwan
 * @Description:
 * @Date: create in 2022/1/12/012
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartmentService departmentService;


    @RequestMapping("/emps")
    public String queryAllEmployee(Model model) {
        List<Employee> emps = employeeService.queryAllEmployee();
        model.addAttribute("emps", emps);
        List<Department> departments = departmentService.getDepatments();
        model.addAttribute("departments", departments);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAdd(Model model) {
        List<Department> departments = departmentService.getDepatments();
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String add(Employee employee) {
        employee.setCreateDate(new Date());
        employeeService.add(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/upemp/{id}")
    public String toUpdata(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeService.getEmployeeById(id);
        model.addAttribute("emp", employee);
        List<Department> departments = departmentService.getDepatments();
        model.addAttribute("departments", departments);
        return "emp/update";
    }

    @RequestMapping("/updateEmp")
    public String updateEmp(Employee employee) {
        employeeService.upById(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/delemp/{id}")
    public String delId(@PathVariable("id") Integer id) {
        employeeService.delById(id);
        return "redirect:/emps";
    }
}
